from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirect
from .models import User,Article,Topic,Comment
import os
import time
from PIL import Image
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
'''
@登录
'''
def login(request):
    if (request.method == "POST"):
        username = request.POST["username"]
        passwd = request.POST["passwd"]
        islogin = User.objects.filter(username__exact=username, password__exact=passwd)
        if (islogin):
            request.session["userlogin"] = username
            return HttpResponseRedirect("/topiclist")
        else:
            return HttpResponse("登录失败")
    return render(request,"login.html")

'''
@注册
'''
def register(request):
    if (request.method == 'POST'):
        username = request.POST["username"]
        passwd = request.POST["passwd"]
        phone = request.POST["phone"]
        email = request.POST["email"]
        isadmin = False
        User.objects.create(username=username, password=passwd, phone=phone, email=email, isadmin=isadmin, )
        request.session["userlogin"] = username
        return HttpResponseRedirect("/topiclist")
    return render(request, "register.html")

'''
@发布话题
'''
def release(request):
    if request.session.has_key("userlogin"):
        username=request.session["userlogin"]
        a="退出"
        b="/logout"
        if(request.method=="POST"):
            title=request.POST["topictitle"]
            author=User.objects.get(username=username)
            content=request.POST["content"]
            brief=request.POST["brief"]
            type=request.POST["type"]

            #把图片存至mypics文件夹中
            mypic=request.FILES.get('picture')
            sname="mypics/"+ str(time.time()) +".jpg"
            cname = BASE_DIR +"/static/" +sname

            img=open(cname,"wb+")
            for chunk in mypic.chunks():
                img.write(chunk)

            img.close()
            im=Image.open(cname)
            im.thumbnail((200,150))
            os.remove(cname)
            im.save(cname,None)


            typef=Topic.objects.get(topicname=type)
            if(typef):
                Article.objects.create(title=title,content=content,brief=brief,author=author,topic=typef,image=sname)
                return HttpResponseRedirect("/topiclist")
            else:
                return HttpResponse(typef)
        return render(request,"release.html",{"username":username,"a":a,"b":b,})
    else:
        return  HttpResponseRedirect("/login")

'''
@退出
'''
def logout(request):
    del request.session["userlogin"]
    return HttpResponseRedirect("/topiclist")
'''
@话题主页
'''
def topiclist(request):
    if request.session.has_key("userlogin"):
        username = request.session["userlogin"]
        a = "退出"
        b = "/logout"
        topic=Topic.objects.values("topicname")
        articles=Article.objects.all().values("title","author","time","brief","topic","id",)
        for i in range(0,len(articles)):
            tid=articles[i]["topic"]
            aid=articles[i]["author"]
            articles[i]["topic"]=Topic.objects.filter(id=tid).values("topicname")[0]["topicname"]
            articles[i]["author"]=User.objects.filter(id=aid).values("username")[0]["username"]
        return render(request,"topiclist.html",{"username":username,
                                            "a":a,
                                            "b":b,
                                            "topic":topic,
                                            "articles":articles,
                                            })
    else:
        a = "请登录"
        b = "/login"
        topic = Topic.objects.values("topicname")
        articles = Article.objects.all().values("title", "author", "time", "brief","topic","id", )

        for i in range(0, len(articles)):
            tid = articles[i]["topic"]
            aid = articles[i]["author"]
            articles[i]["topic"] = Topic.objects.filter(id=tid).values("topicname")[0]["topicname"]
            articles[i]["author"] = User.objects.filter(id=aid).values("username")[0]["username"]
        return render(request, "topiclist.html", {
                                                  "a": a,
                                                  "b": b,
                                                  "topic": topic,
                                                  "articles": articles, })

'''
@话题分类
'''
def topics(request,topicname):
    if request.session.has_key("userlogin"):
        username = request.session["userlogin"]
        a = "退出"
        b = "/logout"
        topic = Topic.objects.values("topicname")
        try:
            rst=Topic.objects.filter(topicname__exact=topicname).values("id")[0]["id"]
            articles=Article.objects.filter(topic__exact=rst).values("title", "author", "time", "brief","id", )

            for i in range(0, len(articles)):
                aid = articles[i]["author"]
                articles[i]["author"] = User.objects.filter(id=aid).values("username")[0]["username"]

            return render(request,"topics.html",{"username":username,
                                                 "a":a,
                                                 "b":b,
                                                 "articles":articles,
                                                 "topicname":topicname,
                                                 "topic":topic,})
        except Exception as err:
            return HttpResponse("您所要找的话题类别不存在")
    else:
        a = "请登录"
        b = "/login"
        topic = Topic.objects.values("topicname")
        rst = Topic.objects.filter(topicname__exact=topicname).values("id")[0]["id"]

        try:
            articles = Article.objects.filter(topic__exact=rst).values("title", "author", "time", "brief","id", )
            for i in range(0, len(articles)):
                aid = articles[i]["author"]
                articles[i]["author"] = User.objects.filter(id=aid).values("username")[0]["username"]
            return render(request, "topics.html", {"a": a,
                                                   "b": b,
                                                   "articles": articles,
                                                   "topicname":topicname,
                                                   "topic":topic,})
        except Exception as err:
            return HttpResponse("您所要找的话题类别不存在")



'''
@文章详情页
'''
def details(request,articlesid):
    if request.session.has_key("userlogin"):
        article=Article.objects.get(id=articlesid)
        id=articlesid
        comment = Comment.objects.all().values("comment_author","comment_time","content")
        return render(request,"articledetails.html",{
                                    "article":article,
                                    "comment":comment,
                                    "id":id,})
    else:
        article = Article.objects.get(id=articlesid)
        comment = Comment.objects.all().values("comment_author", "comment_time", "content")
        a="登录后才可以发布评论"
        return render(request, "articledetails.html", {
            "article":article,
            "comment": comment,
            "a":a,
            "id":id, })
def comment(request,id):
    author=request.session["userlogin"]
    article=Article.objects.get(id=id)
    comments = request.POST["thiscomment"]
    Comment.objects.create(content=comments, comment_author=author, article=article)
    comment = Comment.objects.all().values("comment_author", "comment_time", "content")
    return render(request, "articledetails.html", {
        "comment": comment,
        "article":article,})
